<template>
  <el-dialog
    title="基本信息"
    :visible.sync="visible"
    :append-to-body="true">
    <el-tabs v-model="activeName"  @tab-click="handleClick">
      <el-tab-pane label="基本信息" name="first">
        <el-form :model="dataForm1" ref="dataForm1" @keyup.enter.native="dataFormSubmit1()" label-width="80px">
          <el-form-item label="所属小区" prop="housingEstateName">
            <span>{{ dataForm1.housingEstateName }}</span>
          </el-form-item>
          <el-form-item label="账号">
            <span>{{ userName }}</span>
          </el-form-item>
          <el-form-item :label="$t('form.nickname')" prop="nickName">
            <el-input v-model="dataForm1.nickName"
            placeholder="昵称"></el-input>
          </el-form-item>
          <el-form-item :label="$t('form.contactWay')" prop="phone">
            <el-input v-model="dataForm1.phone"
            placeholder="联系方式"></el-input>
          </el-form-item>
          <el-form-item label="头像">
            <el-upload
              ref="upload"
              class="avatar-uploader"
              action="/clientauth/client/upload"
              :show-file-list="false"
              :on-error="handleError"
              :on-success="handleAvatarSuccess"
              :headers="headers"
              :before-upload="beforeAvatarUpload">
              <img v-if="dataForm1.avatar" :src="this.imgUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
      </el-form-item>
          <span  class="dialog-footer">
            <el-button @click="visible = false">{{ $t('handle.cancel') }}</el-button>
            <el-button type="primary" @click="dataFormSubmit1()">{{ $t('handle.confirm') }}</el-button>
          </span>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="修改密码" name="second">
        <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
          <el-form-item label="原密码" prop="password">
            <el-input type="password" v-model="dataForm.password"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newpassword1">
            <el-input type="password" v-model="dataForm.newpassword1"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="newpassword2">
            <el-input type="password" v-model="dataForm.newpassword2"></el-input>
          </el-form-item>
        </el-form>
        <span  class="dialog-footer">
          <el-button @click="visible = false">{{ $t('handle.cancel') }}</el-button>
          <el-button type="primary" @click="dataFormSubmit()">{{ $t('handle.confirm') }}</el-button>
        </span>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<script>
import Vue from "vue";
import { clearLoginInfo } from "@/utils";
import { imgUrlHost } from "@/config/env";
export default {
  data() {
    var validateConfirmPassword = (rule, value, callback) => {
      if (this.dataForm.newpassword1 !== value) {
        callback(new Error("确认密码与新密码不一致"));
      } else {
        callback();
      }
    };
    return {
      imgUrlHost: imgUrlHost,
      imgUrl: "",
      headers: {
        Authorization: "Bearer " + Vue.cookie.get("access-token")
      },
      activeName: "first",
      visible: false,
      dataForm: {
        password: "",
        newpassword1: "",
        newpassword2: ""
      },
      dataForm1: {
        id: "",
        username: "",
        phone: "",
        dgUserId: "",
        avatar: "",
        housingEstateId: "",
        superAdmin: "",
        housingEstateName: "",
        nickName:"",
      },
      dataRule: {
        password: [
          { required: true, message: "原密码不能为空", trigger: "blur" }
        ],
        newpassword1: [
          { required: true, message: "新密码不能为空", trigger: "blur" }
        ],
        newpassword2: [
          { required: true, message: "确认密码不能为空", trigger: "blur" },
          { validator: validateConfirmPassword, trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    userName: {
      get() {
        return this.$store.state.user.name;
      }
    },
    nickName: {
      get() {
        return this.$store.state.user.nickname;
      }
    },
    mainTabs: {
      get() {
        return this.$store.state.common.mainTabs;
      },
      set(val) {
        this.$store.commit("common/updateMainTabs", val);
      }
    }
  },
  methods: {
    // 文件上传成功时调用
    handleAvatarSuccess(response, file) {
      //  this.dataForm.avatar = URL.createObjectURL(file.raw);
      this.imgUrl = imgUrlHost + response.iconName;
      this.dataForm1.avatar = response.iconName;
    },
    // 文件上传失败时调用
    handleError(err, file, fileList) {
      this.$message.error("文件上传失败");
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      let fileFlag = false;
      if (isJPG || isPNG) {
        fileFlag = true;
      } else {
        this.$message.error("上传头像图片只能是 JPG 格式或 PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }

      /**************************** */
      const isSize = true;
      // const isSize = new Promise(function(resolve, reject) {
      //   let width = 750; // 限制图片尺寸为654X270
      //   let height = 279;
      //   let _URL = window.URL || window.webkitURL;
      //   let img = new Image();
      //   img.onload = function() {
      //     let valid = img.width === width && img.height === height;
      //     valid ? resolve() : reject();
      //   };
      //   img.src = _URL.createObjectURL(file);
      // }).then(
      //   () => {
      //     return file;
      //   },
      //   () => {
      //     this.$message.error("图片尺寸限制为750 x 279");
      //     return Promise.reject();
      //   }
      // );

      return fileFlag && isLt2M && isSize;
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    // 初始化
    init() {
       console.log("");
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
      });
      // 请求本人数据
      this.$http({
        url: `/dg-ic/ic/sys/user/info/` + this.$store.state.user.userId,
        method: "get",
        params: this.$http.adornParams()
      }).then(
        ({ data }) => {
          if (data && data.code === 0) {
            this.dataForm1.id = data.data.id;
            this.dataForm1.username = data.data.username;
            this.dataForm1.phone = data.data.phone;
            this.dataForm1.dgUserId = data.data.dgUserId;
            this.dataForm1.housingEstateName = data.data.housingEstateName;
            this.dataForm1.superAdmin = data.data.superAdmin;
            this.dataForm1.avatar = data.data.avatar;
            this.dataForm1.nickName = data.data.nickName;
            this.imgUrl = imgUrlHost + data.data.avatar;
          } else {
            this.$message.error(data.msg);
          }
        },
        error => {
          if (error.response.status === 403) {
            this.$message.error("你没有权限");
          } else {
            this.$message.error("系统错误，请联系管理员");
          }
        }
      );
    },
    // 基本信息表单提交
    dataFormSubmit1() {
      this.$refs["dataForm1"].validate(valid => {
        if (valid) {
          this.$http({
            // url: this.$http.adornUrl('/sys/user/password'),
            url: "/dg-ic/ic/sys/user/update",
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm1.id,
              phone: this.dataForm1.phone,
              avatar: this.dataForm1.avatar,
              username: this.dataForm1.username,
              dgUserId: this.dataForm1.dgUserId,
              nickName: this.dataForm1.nickName,
              // 后续的字段后续加上
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$nextTick(() => {
                    this.$store.commit('user/avatar', this.dataForm1.avatar)
                    this.$store.commit('user/nickname', this.dataForm1.nickName)
                  });
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$http({
            // url: this.$http.adornUrl('/sys/user/password'),
            url: "/clientauth/user/editInfo",
            method: "put",
            // data: this.$http.adornData({
            //   'password': this.dataForm.password,
            //   'newPassword': this.dataForm.newPassword
            // })
            data: this.dataForm
          }).then(({ data }) => {
            if (data && data.code === 0) {
              if (!data.data) {
                this.$message.error(data.msg);
              } else {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.$nextTick(() => {
                      this.mainTabs = [];
                      clearLoginInfo();
                      this.$router.replace({ name: "login" });
                    });
                  }
                });
              }
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    }
  }
};
</script>

